// pages/message/message.js

let md5 = require("../../utils/md5.js")
let axios = require("../../utils/util.js")
let app = getApp()
import {
  IMSDK
} from '../../utils/common';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    Sum_: 0,
    statusBarHeight: '44',
    poabsolute: 32,
    roomid: '',
    messageTop: ["聊天", "好友", "关注", "粉丝"],
    messageList_liaot: [], //信息列表
    followList: "", //关注列表
    fansList: "", //粉丝列表
    systemobj: "", //系统消息/互动消息
    userInfo: '', //微信用户信息
    goodFriend: [], //好友信息
    ishongdian: 0, //新信息
    arrunreadCount: [], //未读信息
    user_list: {}, //用户信息
    input1: '',
    // touchS : [0,0],
    // touchE : [0,0]
    startX: 0, //开始坐标
    startY: 0,

    currentTab: 0,
    navScrollLeft: 0,
    winWidth: 0,
    winHeight: 0,
  },
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.messageList_liaot.forEach(function (v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      messageList_liaot: this.data.messageList_liaot
    })
  },
  // 截获竖向滑动
  catchTouchMove(e) {
    return true
  },
  // 滚动切换标签样式 
  switchTab: function (e) {
    var that = this;
    that.setData({
      poabsolute: 32 + e.detail.current * 106,
      currentTab: e.detail.current,
    });
    this.mesChange(e.detail.current)
  },

  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.messageList_liaot.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      messageList_liaot: that.data.messageList_liaot
    })
  },

  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */

  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  //删除事件

  del: function (e) {
    Dialog.confirm({
      selector: '#myDialog',
      title: '忽略未读',
      message: '消息气泡会清除，但消息不会丢失，会显示“已读”',
      confirmButtonColor: "#0091FF",
      cancelButtonColor: "#A8ABAE",
    }).then((res) => {
      // console.log('openDialog',res)
      // this.Message_(e.currentTarget.dataset.indexs.conversationID)//会话已读
      this.delete(e.currentTarget.dataset.indexs.conversationID) //删除会话
      this.data.messageList_liaot.splice(e.currentTarget.dataset.index, 1)
      this.setData({
        messageList_liaot: this.data.messageList_liaot
      })
    }).catch((error) => {
      // console.log('openDialog error',error)
    })

  },
  Message_(c2c_id) {
    this.data.tim.setMessageRead({
      conversationID: c2c_id
    });
  },
  delete(c2c_id) {
    let promise = this.data.tim.deleteConversation(c2c_id);
    promise.then(function (imResponse) {
      // 删除会话成功
      const {
        conversationID
      } = imResponse.data; // 被删除的会话 ID
      // console.log(conversationID);
    }).catch(function (imError) {
      console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
    });
  },

  input1(e) {
    this.setData({
      input1: e.detail.value
    })
  },

  //搜索
  tosearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  //清除未读信息
  // eliminate() {
  //   if (this.data.arrunreadCount.length > 0) {
  //     this.data.arrunreadCount.forEach(item => { 
  //       console.log(item);
  //       this.data.tim.setMessageRead({
  //         conversationID: item 
  //       });
  //     });
  //   }
  // },
  tabMessage(index) {
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
    };
    switch (index) {
      case 0:
        this.giv_info()
        break;
      case 1:
        axios.axios({
          url: "/message/friend",
          data: params
        }).then((res) => {
          this.setData({
            goodFriend: res.data.result,
          })
        })
        break;
      case 2:
        axios.axios({
          url: "/user/followList",
          data: params
        }).then((res) => {
          this.setData({
            followList: res.data.result,
          })
        })
        break;
      case 3:
        axios.axios({
          url: "/user/fansList",
          data: params
        }).then((res) => {
          this.setData({
            fansList: res.data.result,
          })
        })
        break;
    }
  },
  // 顶部切换
  mesChange(data) {
    let index;
    if (typeof (data) === "object") {
      console.log("object");
      index = data.currentTarget.dataset.index;
      this.setData({
        currentTab: index,
      })
    } else {
      // console.log("number");
      index = data;
    }
    this.tabMessage(index)
  },
  //消息详情
  tomessage(data) {
    let datas = JSON.stringify(data.currentTarget.dataset.indexs)

    // console.log(data.currentTarget.dataset.indexs.conversationID);
    // 将某会话下所有未读消息已读上报
    let promise = this.data.tim.setMessageRead({
      conversationID: data.currentTarget.dataset.indexs.conversationID
    });
    promise.then(function (imResponse) {
      // 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
      console.log('成功:', imResponse);
      if (data.currentTarget.dataset.indexs.conversationID == "C2C102") {
        wx.navigateTo({
          url: '/pages/systemMes/systemMes'
        })
      } else if (data.currentTarget.dataset.indexs.conversationID == "C2C100") {
        wx.navigateTo({
          url: '/pages/systemInformation/systemInformation'
        })
      } else {
        wx.navigateTo({
          url: '/pages/messageInfo/messageInfo?index=' + encodeURIComponent(datas),
        })
      }
    }).catch(function (imError) {
      // 已读上报失败
      console.warn('失败:', imError);
    });

  },
  //好友去聊天
  tomessigeinfo(data) {
    let hi = data.currentTarget.dataset.index
    let datas = JSON.stringify(hi)
    wx.navigateTo({
      url: '/pages/messageInfo/messageInfo?list_xd=' + encodeURIComponent(datas),
    })
  },
  //去他人主页
  tomemberId(data) {
    wx.navigateTo({
      url: '/pages/me/me?memberId=' + data.currentTarget.dataset.perfectnumber,
    })
  },
  //系统消息
  tosystemMes() {
    wx.navigateTo({
      url: '/pages/systemMes/systemMes'
    })
  },
  //互动消息
  tointeractMes() {
    wx.navigateTo({
      url: '/pages/systemInformation/systemInformation'
    })
  },

  //取消关注
  unfollow(data) {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&followId=" +
      this.data.followList[data.currentTarget.dataset.index].userId +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      followId: this.data.followList[data.currentTarget.dataset.index].userId,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/followCancel",
      data: params
    }).then((res) => {
      console.log(res.data),
        wx.showToast({
          title: res.data.text,
          icon: 'none'
        })
      this.getfollow()
    })
  },
  tofollow(data) {
    console.log(data.currentTarget.dataset.isfollow);
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&followId=" +
      this.data.fansList[data.currentTarget.dataset.index].userId +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      followId: this.data.fansList[data.currentTarget.dataset.index].userId,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    if (!this.data.fansList[data.currentTarget.dataset.index].isFollowEachOther) {
      axios.axios({
        url: "/user/followInsert",
        data: params
      }).then((res) => {
        console.log(res.data),
          wx.showToast({
            title: res.data.text,
            icon: 'none'
          })
        this.getfans()
      })
    } else {
      axios.axios({
        url: "/user/followCancel",
        data: params
      }).then((res) => {
        console.log(res.data),
          wx.showToast({
            title: res.data.text,
            icon: 'none'
          })
        this.getfans()
      })
    }
  },
  //获取参数
  giv_info() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/message/syslist",
      data: params
    }).then((res) => {
      // console.log(res.data.result)
      // var sum = Number(res.data.result.sysCountUnread) + Number(res.data.result.callCountUnread);
      this.setData({
        systemobj: res.data.result
        // ishongdian: sum
      })

    })
  },

  changeType(data) {
    getApp().preventActive(() => { //防止多次点击
      let roomId = data.currentTarget.dataset.roomid
      console.log(roomId);
      this.setData({
        roomid: roomId.room_id,
      })
      if (this.data.user_list.isAuth == 0 && roomId.room_id == '-1') {
        wx.showToast({
          title: "请实名后创建房间",
          icon: 'none',
          duration: 2000 //持续的时间
        })
        return
      } else if (this.data.user_list.isAuth == 1 && roomId.room_id == '-1') {
        return this.myRoomId()
      } else {
        wx.navigateTo({
          url: '/pages/room/room?roomId=' + roomId.room_id,
        })
      }

    })
  },
  //进入我的房间
  myRoomId() {
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
    };
    axios.axios({
      url: "/chat/myRoomId",
      data: params
    }).then((res) => {
      if (res.data.status == '0') {
        this.setData({
          roomid: res.data.result.room_id
        })
        wx.navigateTo({
          url: '/pages/room/room?roomId=' + this.data.roomid + '&password=' + this.data.password,
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  //加入房间
  joinRoom() {

    let params = {
      roomId: this.data.roomid,
      userId: app.globalData.user_id.toString(),
      token: app.globalData.userToken,
      shumeiDeviceId: wx.getStorageSync('shumeiDeviceId'),
      clientId: wx.getStorageSync('getClientId')
    };
    axios.axios({
      url: "/chat/joinRoom",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        wx.navigateTo({
          url: '/pages/room/room?roomId=' + this.data.roomid + '&password=' + this.data.password,
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  getfollow() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/followList",
      data: params
    }).then((res) => {
      console.log(res.data.result),
        this.setData({
          followList: res.data.result
        })
    })
  },
  getfans() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/fansList",
      data: params
    }).then((res) => {
      console.log(res.data.result),
        this.setData({
          fansList: res.data.result
        })
    })
  },
  stopTouchMove() {},
  switchNav: function (e) {
    console.log(e.currentTarget.dataset.current)
    var that = this
    var cur = e.currentTarget.dataset.current;
    if (that.data.currentTab == cur) {
      return false;
    } else {
      that.setData({
        currentTab: cur
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user_list = wx.getStorageSync('UserInformation')
    if (user_list) {
      app.globalData.userInfo = user_list
      app.globalData.user_id = user_list.userId;
      app.globalData.userToken = user_list.token;
      app.globalData.perfectNumber = user_list.perfectNumber;
      this.giv_info()
      let that = this;
      wx.getSystemInfo({
        success: res => {
          that.setData({
            statusBarHeight: res.statusBarHeight,
            user_list: user_list,
            // Sum_:app.globalData.Sum_,
          })
        },
      });
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
    var that = this;
    /** 获取系统信息*/
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight,
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2,
      })
    }
    let tim;
    let messageList_liaot = wx.getStorageSync('messageList_liaot')
    tim = IMSDK(this)
    this.setData({
      tim,
      messageList_liaot,
    })
    this.giv_info()
  },
  //获取用户openid
  get_openId() {
    wx.login({
      success: res => {
        // console.log(res);
        let timestamp = (Date.parse(new Date()) / 1000).toString();
        let arys = {
          code: res.code,
          type: "2",
          time: timestamp,
        };
        let _token = axios.encryption(arys);
        let params = {
          code: res.code,
          time: timestamp,
          type: "2",
          sign: md5.hexMD5(_token),
        };
        axios.axios({
          url: "/index/getOpenId",
          data: params
        }).then((res) => {
          // console.log(res.data.result);
          this.wxdenglu(res.data.result)
        })
      }
    })
  },
  //微信登录
  wxdenglu(event) {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    console.log(this.data.userInfo);
    let data = {
      "city": this.data.userInfo.city,
      "country": this.data.userInfo.country,
      "headimgurl": this.data.userInfo.avatarUrl,
      "nickname": this.data.userInfo.nickName,
      "openid": event.openid,
      "province": this.data.userInfo.province,
      "sex": "1",
      "unionid": event.unionid
    }
    console.log(data);
    let arys = {
      data: JSON.stringify(data),
      type: "1",
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      data: JSON.stringify(data),
      type: "1",
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/thirdLoginV2",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        wx.showToast({
          title: "登录成功",
          icon: 'none',
          duration: 2000 //持续的时间
        })
        wx.setStorageSync('UserInformation', res.data.result)
      } else {
        this.wxzhuce(event)
        setTimeout
      }
    })
  },
  //微信注册
  wxzhuce(event) {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    console.log(this.data.userInfo);
    let arys = {
      nickname: this.data.userInfo.nickName,
      sex: "1",
      birthday: "1999-09-26",
      invitedId: "",
      headpic: this.data.userInfo.avatarUrl,
      type: "1",
      openid: event.openid,
      unionid: event.unionid,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      nickname: this.data.userInfo.nickName,
      sex: "1",
      birthday: "1999-09-26",
      invitedId: "",
      headpic: this.data.userInfo.avatarUrl,
      type: "1",
      openid: event.openid,
      unionid: event.unionid,
      sign: md5.hexMD5(_token),
      shumeiDeviceId: wx.getStorageSync('shumeiDeviceId'),
    };
    axios.axios({
      url: "/user/reg",
      data: params
    }).then((res) => {

      console.log(res);
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let user_list = wx.getStorageSync('UserInformation')
    app.globalData.userInfo = user_list
    app.globalData.user_id = user_list.userId;
    app.globalData.userToken = user_list.token;
    app.globalData.perfectNumber = user_list.perfectNumber;
    this.giv_info()
    this.setData({
      user_list
    })
    var t;
    let _ = this;
    clearTimeout(t);
    t = setTimeout(function () {
      wx.stopPullDownRefresh(); //停止当前页面下拉刷新
      return wx.showToast({
        title: "刷新成功",
        icon: 'none',
        duration: 2000
      })
    }, 1000);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
